import tornado.httpserver
import tornado.ioloop
import tornado.options
import os.path
import tornado.web
import logging
import sys
import time
import json
from bson import ObjectId
from tornado.web import asynchronous
from tornado.gen import coroutine
from motor import MotorClient
from tornado.options import define, options
from util.function import JSONEncoder

define("port", default=8007, help="项目运行的端口，默认8007", type="int")
define("mongo_host", default="mongodb://127.0.0.1:27017",help="app database host")
define("mongo_db", default="demo_001", help="app database name")

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")

handlers = [
            (r"/", IndexHandler),
            (r"/login", "handlers.auth.LoginHandler"),
            (r"/register", "handlers.auth.RegisterHandler"),
            (r"/info", "handlers.user.InfoHandler"),
        ]

settings = {
        "template_path": os.path.join(os.path.dirname(__file__), "templates"),
        "static_path": os.path.join(os.path.dirname(__file__), "static"),
        "session": {
			"driver": "redis",
			"driver_settings": {
				"host": "localhost",
				"port": 6379,
				"db": 1
			}
		},
        "debug": True,
    }

# 数据库
try:
    client = MotorClient(options.mongo_host) # 创建Mongodb实例
    database = client[options.mongo_db] # 获取数据库名，另外一种写法client.db_name
    settings["database"] = database # 将数据库设置到setting中
except e:
    logging.error("cannot connect mongodb")
    sys.exit(0)
    
class Application(tornado.web.Application):
    def __init__(self):
        tornado.web.Application.__init__(self, handlers=handlers, **settings)

if __name__ == "__main__":
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    logging.info("servers running on http://192.168.137.133:%d" % (options.port))
    tornado.ioloop.IOLoop.instance().start()